'use strict';
const {
  regNormal,
  regPhone,
  regPwd,
  regEmail,
  regNumber,
  regSex,
} = require('../utils/regModel');
const { lack } = require('../utils/resModel');
const _ = require('lodash');

const extraCheck = (targetVal, targetName) => {
  switch (targetName) {
    case 'phone':
    case 'tel':
      return regPhone(targetVal);
    case 'mail':
    case 'pwd':
      return regPwd(targetVal); //用户密码的正则校验
    case 'email':
      return regEmail(targetVal);
    case 'user_id':
    case 'carousel_id':
      return regNumber(targetVal);
    case 'sex':
      return regSex(targetVal);
    default:
      return regNormal(targetVal);
  }
};

class checkData {
  constructor(_this, ...targetArr) {
    let is_pass = true;
    const dataObj = _.isEmpty(_this.ctx.request.body)
      ? _this.ctx.query
      : _this.ctx.request.body;
    targetArr = [].concat.apply([], targetArr);
    if (targetArr.length) {
      // 有指定检测的参数
      for (const key of targetArr) {
        if (!dataObj[`${key}`] || !extraCheck(dataObj[`${key}`], key)) {
          is_pass = key;
          break;
        }
      }
    } else {
      // 没有指定参数,需要将全部参数进行检测
      for (const k in dataObj) {
        if (!regNormal(dataObj[k])) {
          is_pass = k;
        }
      }
    }
    this.checkDataRes = typeof is_pass === 'boolean';
    if (!this.checkDataRes) {
      _this.ctx.body = lack(is_pass);
    }
  }
}

module.exports = { checkData };
